import 'package:flutter/material.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/model/user_list_model.dart';
import 'package:gold/ui/my/order/authorization_collect_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// @description: 授权提货页面
/// @author tangzhentao
/// @created at 22:49 2025/2/27

class AuthorizationCollectPage extends StatelessWidget {
  /// 订单信息
  final OrderModel order;

  /// 状态控制器
  late final AuthorizationCollectViewmodel _authorizationVM;
  /// 选中授权人
  final ValueNotifier<SearchUserModel?> _userNotifier = ValueNotifier(null);

  AuthorizationCollectPage({super.key, required this.order}) {
    _authorizationVM = AuthorizationCollectViewmodel(order.id!);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          appBar: xfgAppbar(title: '授权提货'),
          body: Padding(
            padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, 0),
            child: Column(
              children: [
                _getOrderAndProductInfoWidget(),
                Expanded(
                    child: Container(
                      decoration: white6Decoration,
                      margin: EdgeInsets.only(top: XfgSize().size10),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, 0),
                            height: XfgSize().size44,
                            decoration: bottomBorderDecoration,
                            child: ValueListenableBuilder<SearchUserModel?>(
                              valueListenable: _userNotifier,
                              builder: (_, user, __) => Row(
                                children: [
                                  Expanded(child: XfgText(user?.nickname?? '受让人', fontSize: XfgSize().text14, color: user != null ? XfgColor.text1D:XfgColor.text3)),
                                  TextButton(
                                      onPressed: user == null ? null: () => _authorizationVM.confirmAuthorization(user),
                                      style: xfgButtonStyle(Size(XfgSize().size97, XfgSize().size32), radius: XfgSize().size32, color: XfgColor.colorF2),
                                      child: XfgText('确认授权', fontSize: XfgSize().text14, color: user == null ? XfgColor.text3:XfgColor.text1D, bold: FontWeight.bold)
                                  ),
                                ],
                              ),
                            ),
                          ),
                          /// 受让人搜索
                          Container(
                              height: XfgSize().size44,
                              margin: EdgeInsets.all(XfgSize().size10),
                              decoration: BoxDecoration(border: Border.all(width: XfgSize().size0_5, color: XfgColor.colorE)),
                              child: Row(
                                children: [
                                  SizedBox(width: XfgSize().size10),
                                  Expanded(
                                    child: TextField(
                                      style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text1D),
                                      controller: _authorizationVM.editingController,
                                      focusNode: _authorizationVM.foucsNode,
                                      onSubmitted: (value) => _authorizationVM.search(),
                                      decoration: InputDecoration(
                                        isDense: true,
                                        isCollapsed: true,
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.only(left: XfgSize().size8),
                                        hintText: '请输入手机号/姓名',
                                        hintStyle: TextStyle(fontSize: XfgSize().text14, color: XfgColor.text3),
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: XfgSize().size10),
                                  GestureDetector(
                                    onTap: _authorizationVM.search,
                                    child: Image.asset(Res.imagesIntegralSearch, width: XfgSize().size20, height: XfgSize().size20),
                                  ),
                                  SizedBox(width: XfgSize().size14),
                                ],
                              )
                          ),
                          /// 搜索结果
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.only(bottom: XfgSize().bottomBarHeight == 0 ? XfgSize().size10:XfgSize().bottomBarHeight),
                              child: ProviderWidget<AuthorizationCollectViewmodel>(
                                model: _authorizationVM,
                                builder: (ctx, authorization) => SmartRefresher(
                                  controller: authorization.controller,
                                  enablePullUp: true,
                                  enablePullDown: true,
                                  onRefresh: authorization.refresh,
                                  onLoading: authorization.loadMore,
                                  child: ListView.builder(
                                    itemCount: authorization.userList.length,
                                    itemBuilder: (_, index) {
                                      final user = authorization.userList[index];
                                      final select = authorization.selectIndex;
                                      return GestureDetector(
                                        onTap: () {
                                          if (select != index) {
                                            _userNotifier.value = authorization.userList[index];
                                            authorization.changeSelect(index);
                                          }
                                        },
                                        child: Container(
                                          margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, 0),
                                          height: XfgSize().size44,
                                          padding: EdgeInsets.symmetric(horizontal: XfgSize().size14),
                                          alignment: Alignment.centerLeft,
                                          color: select == index ? XfgColor.colorF2:XfgColor.transparent,
                                          child: XfgText(user.nickname?? '--', fontSize: XfgSize().text14, color: XfgColor.text1D),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    )
                )
              ],
            ),
          )
      ),
    );
  }

  /// 订单&商品信息
  Widget _getOrderAndProductInfoWidget() {
    final logo = order.detail?.product?.coverImage;
    final orderNo = order.orderNo?? '';
    final productName = order.detail?.product?.name?? '';
    final quantity = order.quantity?.toString()?? '1';
    final createdAt = order.createdAt?? '';
    return Container(
      decoration: white10Decoration,
      child: Column(
        children: [
          Container(
            height: XfgSize().size49,
            padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
            child: Row(
              children: [
                Expanded(child: XfgText('订单号:$orderNo', fontSize: XfgSize().text14, color: XfgColor.text1)),
                XfgText('待提货', fontSize: XfgSize().text16, color: XfgColor.theme, bold: FontWeight.bold)
              ],
            ),
          ),
          strokeHeightContainer,
          Padding(
            padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().size8),
            child: SizedBox(
              height: XfgSize().size84,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  HttpImage(logo, size: Size.square(XfgSize().size78), radius: BorderRadius.circular(XfgSize().size6)),
                  SizedBox(width: XfgSize().size12),
                  Expanded(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Expanded(child: XfgText(productName, fontSize: XfgSize().text14, color: XfgColor.text1D, height: 1.5, maxLines: 2)),
                            Container(
                              width: XfgSize().size34,
                              alignment: Alignment.centerRight,
                              child: XfgText('x$quantity', fontSize: XfgSize().text14, color: XfgColor.text1D),
                            )
                          ],
                        ),
                        XfgText(createdAt, fontSize: XfgSize().text12, color: XfgColor.text3),
                        _getTotalPriceWidget()
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
          strokeHeightContainer,
          _getPayWidget(),
        ],
      ),
    );
  }

  /// 获取总价格描述Widget
  Widget _getTotalPriceWidget() {
    final prices = (((order.totalPrice?? 0.0) + (order.freight?? 0.0))).toStringAsFixed(2).split('.');
    final point = order.rewardPoints?? 0;
    final pointStr = point > 0 ? '$point积分':'';
    return Row(
      children: [
        XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.text1D, children: [
          TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
          TextSpan(text: prices.last),
        ]),
        Visibility(
          visible: pointStr.isNotEmpty,
          child: Container(
            margin: EdgeInsets.only(left: XfgSize().size16),
            height: XfgSize().size18,
            width: XfgSize().size12 + boundingTextSize(pointStr, style: TextStyle(fontSize: XfgSize().text12)).width,
            alignment: Alignment.center,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(XfgSize().size2), border: Border.all(color: XfgColor.text3, width: XfgSize().size0_5)),
            child: XfgText(pointStr, fontSize: XfgSize().text12, color: XfgColor.text3),
          ),
        )
      ],
    );
  }

  /// 获取支付描述Widget
  Widget _getPayWidget() {
    final List<Widget> children = [];
    final prices = (((order.payPrice?? 0.00) + (order.amountNum?? 0.00)).toStringAsFixed(2)).split('.');
    final points = (order.pointsPrice?.toDouble().toStringAsFixed(2)?? '0.00').split('.');
    children.addAll([
      XfgText('实际支付', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
      SizedBox(width: XfgSize().size8),
      XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold, children: [
        TextSpan(text: '${prices.first}.', style: TextStyle(fontSize: XfgSize().text20)),
        TextSpan(text: prices.last, style: TextStyle(fontSize: XfgSize().text16)),
      ]),
      SizedBox(width: XfgSize().size16),
      XfgText('积分抵扣', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
      SizedBox(width: XfgSize().size8),
      XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, bold: FontWeight.bold, children: [
        TextSpan(text: '${points.first}.', style: TextStyle(fontSize: XfgSize().text20)),
        TextSpan(text: points.last, style: TextStyle(fontSize: XfgSize().text16)),
      ]),
    ]);
    return Padding(
        padding: EdgeInsets.fromLTRB(0, XfgSize().size22, XfgSize().size18, XfgSize().size16),
        child: Row(mainAxisAlignment: MainAxisAlignment.end, children: children)
    );
  }
}
